﻿/***********************************************************************
 * <copyright file="Model.cs" company="BUCA JSC">
 * -->    Copyright (C) statement. All right reserved
 * </copyright>
 * 
 * Created:   Tuanhm
 * Email:    Tuanhm@humg@gmail.com
 * Website:
 * Create Date: Thursday, March 27, 2014
 * Usage:  
 * 
 * RevisionHistory: 
 * Date         Author               Description 
 * 
 * ************************************************************************/

using System;
using System.ServiceModel;
using WindowsForms.AOnline.Model.AccountingServiceReference;

namespace WindowsForms.AOnline.Model
{
    /// <summary>
    /// Base class for all Repositories. 
    /// Provides common repository functionality, including:
    ///   - Management of Service client.
    ///   - Offers common request-response correlation check.
    /// </summary>
    public abstract class RepositoryBase
    {
        public static IActionAccountingService ActionAccountingServiceBase;
        /// <summary>
        /// Gets the client.
        /// </summary>
        /// <value>
        /// The client.
        /// </value>
        protected static IActionAccountingService Client
        {
            get
            {
                // Check if not initialized yet
                if (ActionAccountingServiceBase == null)
                    ActionAccountingServiceBase = new ActionAccountingServiceClient();

                // If current client is 'faulted' (due to some error), create a new instance.
                var client = ActionAccountingServiceBase as ActionAccountingServiceClient;
                if (client != null && client.State == CommunicationState.Faulted)
                {
                    try { client.Abort(); }
                    catch { /* no action */ }
                }

                return client;
            }
        }

        /// <summary>
        /// Correlates requestid with returned response correlationId. 
        /// These must always match. If not, request and responses are not related.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        protected void Correlate(RequestBase request, ResponseBase response)
        {
            if (request.RequestId != response.CorrelationId)
                throw new ApplicationException("RequestId and CorrelationId do not match.");
        }
    }
}